package framework.controller;

import com.alibaba.fastjson.JSON;
import framework.bo.SysDept;
import framework.common.Common;
import framework.common.ResponseVo;
import framework.service.SysDeptService;
import framework.util._BeanUtil;
import framework.util.layui._LayuiUtil;
import framework.util.layui.TreeVo;
import framework.util.queryFilter.service.impl.QueryFilter;
import framework.util.queryFilter.vo.OrderBy;
import framework.util.queryFilter.vo.Where;
import frameworkExt.util.controller.BaseControllerExt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 吴宇亮 on 2019/2/23 0023 16:20
 */
@Controller
@RequestMapping("/framework/SysDept.do")
public class SysDeptController extends BaseControllerExt {

    @Resource
    private SysDeptService service;

    @ResponseBody
    @RequestMapping(params = "method=list")
    public ResponseVo list(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        QueryFilter filter = new QueryFilter(request, true);
        this.filterDelete(filter);
        filter.orderBy(SysDept.SORT, OrderBy.ASC);
        List<SysDept> list = service.getAll(filter);
        return sendSuccess(list);
    }

    @ResponseBody
    @RequestMapping(params = "method=listTree")
    public ResponseVo listTree(){
        List<TreeVo> result = new ArrayList<>();
        QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
        this.filterDelete(filter);
        filter.where(SysDept.PLID, Where.eq, -1);
        filter.orderBy(SysDept.SORT, OrderBy.ASC);
        List<SysDept> list = service.getAll(filter);
        for (SysDept dept : list) {
            setChildrenDept(dept);
            TreeVo vo = _LayuiUtil.convertToTreeVo(dept, JSON.parseObject("{title: 'cname', children: 'childDepts'}"));
            result.add(vo);
        }
        return sendSuccess(result);
    }

    private void setChildrenDept(SysDept dept){
        if(Common.IS_NO == dept.getHaschild()){
            return;
        }

        //设置子部门
        QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
        this.filterDelete(filter);
        filter.where(SysDept.PLID, Where.eq, dept.getLid());
        filter.orderBy(SysDept.SORT, OrderBy.ASC);
        List<SysDept> childrenDepts = service.getAll(filter);
        dept.setChildDepts(childrenDepts);

        //递归子部门
        for (SysDept childrenDept : childrenDepts) {
            setChildrenDept(childrenDept);
        }
    }

    @ResponseBody
    @RequestMapping(params = "method=add")
    public ResponseVo add(SysDept bo){
        //设置排序
        QueryFilter filter = new QueryFilter(1, Integer.MAX_VALUE);
        this.filterDelete(filter);
        filter.where(SysDept.PLID, Where.eq, bo.getPlid());
        int count = service.getCount(filter);
        bo.setSort(count + 1);
        //设置深度
        SysDept plidDept = service.get(bo.getPlid());
        bo.setDeep(-1 == bo.getPlid() ? 1 : plidDept.getDeep() + 1);
        service.add(bo);
        //设置父节点是否有孩子
        if(null != plidDept && Common.IS_YEW != plidDept.getHaschild()){
            plidDept.setHaschild(Common.IS_YEW);
            service.update(plidDept);
        }
        return sendSuccess();
    }

    @ResponseBody
    @RequestMapping(params = "method=delete")
    public ResponseVo delete(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        String lid = request.getParameter("lid");
        if (StringUtils.isBlank(lid)) {
            return sendFail("参数错误");
        }
        List<SysDept> updateList = new ArrayList<>();

        //删除自己
        SysDept bo = service.get(Integer.valueOf(lid));
        bo.setIsDelete(Common.IS_YEW);
        updateList.add(bo);

        QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
        this.filterDelete(filter);
        filter.where(SysDept.PLID, Where.eq, bo.getPlid());
        filter.where(SysDept.SORT, Where.bigThan, bo.getSort());
        List<SysDept> list = service.getAll(filter);
        for (SysDept sysDept : updateList) {
            sysDept.setSort(sysDept.getSort() - 1);
        }
        updateList.addAll(list);

        //重新判断父节点是否有孩子节点
        if(-1 != bo.getPlid()){
            filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
            this.filterDelete(filter);
            filter.where(SysDept.PLID, Where.eq, bo.getPlid());
            int childrenAmont = service.getCount(filter);
            if(0 == childrenAmont - 1){
                SysDept fatherDept = service.get(bo.getPlid());
                fatherDept.setHaschild(Common.IS_NO);
                updateList.add(fatherDept);
            }
        }

        service.updateBatch(updateList);
        return sendSuccess();
    }

    @RequestMapping(params = "method=toEditOrDetail")
    public ModelAndView toEditOrDetail(ModelAndView model, HttpServletRequest request, HttpServletResponse response) {
        String lid = request.getParameter("lid");
        String pageUrl = request.getParameter("pageUrl");
        if(StringUtils.isAnyBlank(lid, pageUrl)){
            return null;
        }

        SysDept bo = service.get(Integer.valueOf(lid));
        bo.setPdeptName(-1 == bo.getPlid() ? "无" : service.get(bo.getPlid()).getCname());
        model.addObject("bo", bo);
        model.setViewName(pageUrl);
        return model;
    }

    @ResponseBody
    @RequestMapping(params = "method=update")
    public ResponseVo update(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        String lid = request.getParameter("lid");
        if(StringUtils.isBlank(lid)){
            return sendFail("参数错误");
        }

        try {
            SysDept oldBo = service.get(Integer.valueOf(lid));
            _BeanUtil.copyPropertiesFromRequest(oldBo, request);
            service.update(oldBo);
            return sendSuccess();
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }

    /**
     * 上移
     */
    @ResponseBody
    @RequestMapping(params = "method=up")
    public ResponseVo up(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        String lid = request.getParameter("lid");
        if(StringUtils.isBlank(lid)){
            return sendFail("参数错误");
        }
        SysDept bo = service.get(Integer.valueOf(lid));
        if(1 == bo.getSort()){
            return sendFail("已经是最上了！");
        }

        QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
        this.filterDelete(filter);
        filter.where(SysDept.PLID, Where.eq, bo.getPlid());
        filter.where(SysDept.SORT, Where.eq, bo.getSort() - 1);
        List<SysDept> list = service.getAll(filter);
        SysDept upBo = list.get(0);

        bo.setSort(bo.getSort() - 1);
        upBo.setSort(upBo.getSort() + 1);
        service.updateBatch(Arrays.asList(bo, upBo));
        return sendSuccess();
    }

    /**
     * 下移
     */
    @ResponseBody
    @RequestMapping(params = "method=down")
    public ResponseVo down(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        String lid = request.getParameter("lid");
        if(StringUtils.isBlank(lid)){
            return sendFail("参数错误");
        }
        SysDept bo = service.get(Integer.valueOf(lid));
        QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
        this.filterDelete(filter);
        filter.where(SysDept.PLID, Where.eq, bo.getPlid());
        if(service.getCount(filter) == bo.getSort()){
            return sendFail("已经是最下了！");
        }

        filter.where(SysDept.SORT, Where.eq, bo.getSort() + 1);
        List<SysDept> list = service.getAll(filter);
        SysDept downBo = list.get(0);

        bo.setSort(bo.getSort() + 1);
        downBo.setSort(downBo.getSort() - 1);
        service.updateBatch(Arrays.asList(bo, downBo));
        return sendSuccess();
    }

}
